const connection = require("../app/database")

class CommentService {
  async create(momentId,content,userId){
    const statement = `
      INSERT INTO comment (moment_id,content,user_id) VALUES (?,?,?)
    `
    const [result] = await connection.promise().execute(statement,[momentId,content,userId])
    return result
  }

  async reply(momentId,content,commentId,userId){
    const statement = `
    INSERT INTO comment (moment_id,content,comment_id,user_id) VALUES (?,?,?,?)
  `
    const [result] = await connection.promise().execute(statement,[momentId,content,commentId,userId])
    return result
  }

  async update(commentId,content){
    const statement = `
    UPDATE comment set content = ? WHERE id = ?
  `
  try {
    const [result] = await connection.promise().execute(statement,[content,commentId])
    return result
  } catch (error) {
    console.log(error);
  }

  }

  async remove(commentId){
    const statement = `
    DELETE FROM comment WHERE id = ?
  `
    const [result] = await connection.promise().execute(statement,[commentId])
    return result
  }

  async getCommentList(momentId){
    const statement = `
    SELECT 
    c.id,c.content,c.moment_id as momentId , c.comment_id as commentId,c.createAt as createTime,c.updateAt as updateTime,
    JSON_OBJECT('id',u.id,'name',u.name,'createTime',u.createAt,'updateTime',u.updateAt) as user
    FROM comment as c  
    LEFT JOIN user as u ON c.user_id = u.id
    WHERE moment_id = ?
    `
    const [result] = await connection.promise().execute(statement,[momentId])
    return result
  }
}

module.exports = new CommentService()